package main

import (
	"fmt"
	"os"
	"sync"
	"time"
)

type LoggerInterface interface {
	Success(msg string)
	Info(msg string)
	Error(msg string)
	Notice(msg string)
}

type Logger struct {
	f    *os.File
	lock sync.RWMutex
}

func (this *Logger) Success(msg string) {
	info := "SUCCESS: " + msg + "|" + this.GetTime()
	Success(info)
	this.writeLog(info)
}

func (this *Logger) Info(msg string) {
	info := "INFO: " + msg + " | " + this.GetTime()
	Info(info)
	this.writeLog(info)
}

func (this *Logger) Error(msg string) {
	info := "ERROR: " + msg + " | " + this.GetTime()
	Error(info)
	this.writeLog(info)
}

func (this *Logger) Notice(msg string) {
	info := "NOTICE: " + msg + " | " + this.GetTime()
	Notice(info)
	this.writeLog(info)
}

func (this *Logger) GetTime() string {
	timeObj := time.Now()
	year := timeObj.Year()
	month := timeObj.Month()
	day := timeObj.Day()
	hour := timeObj.Hour()
	minute := timeObj.Minute()
	second := timeObj.Second()
	strTime := fmt.Sprintf("%d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, minute, second)
	//注意：%02d 中的 2 表示宽度，如果整数不够 2 列就补上 0
	return strTime
}

func (this *Logger) writeLog(str string) {
	f, err := os.OpenFile("logger.log", os.O_WRONLY, 0644)
	defer f.Close()
	if err != nil {
		panic("\nlogger.log文件打开失败，导致无法写入日志\n")
	}
	this.lock.Lock()
	n, _ := f.Seek(0, 2)
	// 从末尾的偏移量开始写入内容
	_, err = f.WriteAt([]byte(str+"\n"), n)
	this.lock.Unlock()
}
